# !/usr/bin/env python3
# -*- coding: utf-8 -*-


import xml.etree.ElementTree as EleTree
from util.lib import pretty_xml


def _init_fwd_mode_tbl_xml(fwd_mode_set, forward_mode_tbl_xml):
    root = EleTree.Element('fwd_mode_tbl')
    for node in fwd_mode_set:
        node_ele = EleTree.SubElement(root, 'node')
        node_id = EleTree.SubElement(node_ele, 'node_id')
        node_id.text = str(node['node_id'])
        for entry in node['forward_mode_set']:
            entry_ele = EleTree.SubElement(node_ele, 'entry')
            valid_ele = EleTree.SubElement(entry_ele, 'valid')
            valid_ele.text = '1'
            reserve_ele = EleTree.SubElement(entry_ele, 'reserve')
            reserve_ele.text = '0'
            fwd_mode_ele = EleTree.SubElement(entry_ele, 'forward_mode')
            fwd_mode_ele.text = str(entry['forwardmode'])
    tree = EleTree.ElementTree(root)
    pretty_xml(root, '\t', '\n')
    tree.write(forward_mode_tbl_xml,
               encoding='utf-8',
               xml_declaration=True)
    return


def assemble_fwd_mode_tbl(forward_mode_xml, forward_mode_tbl_xml):
    fwd_mode_set = []
    root = EleTree.parse(forward_mode_xml)
    node_ele_set = root.findall('node')
    for node_ele in node_ele_set:
        node = {}
        node_id = node_ele.findtext('node_id')
        node_id = int(node_id, 16)
        node.update({'node_id': node_id})
        forward_mode_set = []
        forward_mode_table = node_ele.find('forward_mode_table')
        entry_set = forward_mode_table.findall('entry')
        for entry in entry_set:
            forwardmode = entry.findtext('forwardmode')
            forwardmode = int(forwardmode, 16)
            forward_mode_set.append({'forwardmode': forwardmode})
        node.update({'forward_mode_set': forward_mode_set})
        fwd_mode_set.append(node)

    _init_fwd_mode_tbl_xml(fwd_mode_set, forward_mode_tbl_xml)

    return


def main():
    forward_mode_xml = '../input/forward_mode.xml'
    forward_mode_tbl_xml = '../output/tbl/forward_mode_tbl.xml'
    assemble_fwd_mode_tbl(forward_mode_xml, forward_mode_tbl_xml)
    return


if __name__ == '__main__':
    main()
